Converting Types |
Objectives |
Discussion |
Converting Data
Dim s as String = "3"
Dim i as Integer
i = cint(s)
Input Boxes
Dim sName as String
sName = InputBox("Enter your name")
Demonstration |
1. Add a new form to your Unit 2 project and make it the startup form.
2. Add a button (btnGetAndAdd) and add the following to the click event:
Dim X As String
Dim Y As String
X = InputBox("Enter a number")
Y = InputBox("Enter another number")
MessageBox.Show(X + Y)
3. Run the program, enter numbers when asked, and observe the result in the messagebox. Notice that the numbers are being added as strings.
4. Modify the code by changing the last line above to:
MessageBox.Show(cint(X) + cint(Y))
5. In this line, we are using the conversion function cint to convert X and Y to integers so that they are added as numbers. Run the program and enter numbers.
6. We are going to modify the code to be very compact. The new compact code will do the same as the above code but with only one line. Comment out all of the code above and type in the following in the click event. Your code should all be on one line or use an underscore to break it into two lines.
MessageBox.Show(CInt(InputBox("Enter a number")) + CInt(InputBox("Enter another number")))
7. Run your program and click the button. This line of code replaced the five previous. The inputboxes return strings, these strings are converted to integers, the integers are added, and the result is displayed in the messagebox. Study this code and make sure that you understand it.
8. Notice when you type in "InputBox(" VS provides a tip about what information needs to be passed into the function. The items in brackets ([ ]) are optional.
Exercises |
1. Write a program that will add two numbers as either integers, singles, or strings. Your program should meet the following specifications:
2. Write statements to complete the following:
Links & Help |